亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將一個值返回給調用異步代碼的函數,然后而不是下一個?

如何將一個值返回給調用異步代碼的函數,然后而不是下一個?

蕭十郎 2022-01-20 18:36:35
如何將值返回給調用異步代碼的函數而不是下一個?出于演示目的,我編寫了以下代碼段來演示我的問題。HTML<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width">    <title>repl.it</title>    <link href="style.css" rel="stylesheet" type="text/css" />  </head>  <body>    <script src="script.js"></script>  </body></html>腳本.jsclass fetchDemo{  constructor(dummy){    this.dummy=dummy    let msg= this.alienMsg();    console.log(msg);  }    alienMsg(){  fetch('./file.txt')  .then(response => response.text())  .then(body =>{     console.log(body);    return body;  })  .then((txt)=>{    console.log(txt)  });  }}new fetchDemo(null);文件.txtI am on a mission to invade earth但是,當您運行它時,您會得到不明確的我的任務是入侵地球我的任務是入侵地球我如何返回以便msg也記錄I am on a mission to invade earth而不是記錄undifined?
查看完整描述

2 回答

?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

JavaScript 是一種同步、阻塞、單線程的語言。這只是意味著一次只能進行一項操作。


嘗試使用回調函數


class fetchDemo{

    constructor(dummy){

      this.dummy=dummy;

      this.alienMsg(function(data) {

        console.log(data);

      });

      

    }

  

    alienMsg(callback){

        fetch('./file.txt')

            .then(response => callback(response.text()))

            .then(body =>{ 

                callback(body);

        })

        .then((txt)=>{

            callback(txt);

        });

    }

  }

  new fetchDemo(null);


查看完整回答
反對 回復 2022-01-20
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

經過不斷嘗試,我暫時使用 JavaScript 承諾解決了這個問題


但是我不會將我的答案標記為正確


注意:我不得不放棄使用 JavaScript 類


var alienMsg = new Promise(

    (res,rej)=>{

    fetch('./file.txt')

  .then(response => response.text())

  .then(body =>{ 

    //console.log(body);

    return body;

  })

  .then((txt)=>{

    //returning inside then using JavaScript promises resolve

    res(txt)

  });

    }

  );


(()=>{

alienMsg

.then(data=> console.log(data));

})();


查看完整回答
反對 回復 2022-01-20
  • 2 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號