第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何將一個值返回給調(diào)用異步代碼的函數(shù),然后而不是下一個?

如何將一個值返回給調(diào)用異步代碼的函數(shù),然后而不是下一個?

蕭十郎 2022-01-20 18:36:35
如何將值返回給調(diào)用異步代碼的函數(shù)而不是下一個?出于演示目的,我編寫了以下代碼段來演示我的問題。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但是,當(dāng)您運行它時,您會得到不明確的我的任務(wù)是入侵地球我的任務(wù)是入侵地球我如何返回以便msg也記錄I am on a mission to invade earth而不是記錄undifined?
查看完整描述

2 回答

?
溫溫醬

TA貢獻1752條經(jīng)驗 獲得超4個贊

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


嘗試使用回調(diào)函數(shù)


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);


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

TA貢獻1784條經(jīng)驗 獲得超9個贊

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


但是我不會將我的答案標(biāo)記為正確


注意:我不得不放棄使用 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));

})();


查看完整回答
反對 回復(fù) 2022-01-20
  • 2 回答
  • 0 關(guān)注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號