如何将一个值返回给调用异步代码的函数,然后而不是下一个?

如何将值返回给调用异步代码的函数而不是下一个?


出于演示目的,我编写了以下代码段来演示我的问题。


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>

脚本.js


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

文件.txt


I am on a mission to invade earth


但是,当您运行它时,您会得到


不明确的


我的任务是入侵地球


我的任务是入侵地球


我如何返回以便msg也记录I am on a mission to invade earth而不是记录undifined?


萧十郎
浏览 151回答 2
2回答

温温酱

JavaScript 是一种同步、阻塞、单线程的语言。这只是意味着一次只能进行一项操作。尝试使用回调函数class fetchDemo{&nbsp; &nbsp; constructor(dummy){&nbsp; &nbsp; &nbsp; this.dummy=dummy;&nbsp; &nbsp; &nbsp; this.alienMsg(function(data) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; alienMsg(callback){&nbsp; &nbsp; &nbsp; &nbsp; fetch('./file.txt')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(response => callback(response.text()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(body =>{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback(body);&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .then((txt)=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback(txt);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; }&nbsp; new fetchDemo(null);

千万里不及你

经过不断尝试,我暂时使用 JavaScript 承诺解决了这个问题但是我不会将我的答案标记为正确注意:我不得不放弃使用 JavaScript 类var alienMsg = new Promise(&nbsp; &nbsp; (res,rej)=>{&nbsp; &nbsp; fetch('./file.txt')&nbsp; .then(response => response.text())&nbsp; .then(body =>{&nbsp;&nbsp; &nbsp; //console.log(body);&nbsp; &nbsp; return body;&nbsp; })&nbsp; .then((txt)=>{&nbsp; &nbsp; //returning inside then using JavaScript promises resolve&nbsp; &nbsp; res(txt)&nbsp; });&nbsp; &nbsp; }&nbsp; );(()=>{alienMsg.then(data=> console.log(data));})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript