我如何从函数 foo 返回一个无同步请求的答案/结果?

我正在尝试从呼叫返回的值,以及将结果分配到函数内部的本地变量,并返回其中一个,但没有这些方式实际上返回答案 - 他们都返回不确定的或无论变量结果的初始值是什么。

一个不同步函数的例子,接受召回(使用 jQuery 的 ajax 函数):

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result; // It always returns `undefined`
}

使用 Node.js 的例子:

function foo() {
    var result;

    fs.readFile("path/to/file", function(err, data) {
        result = data;
        // return data; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}

例如,使用那时承诺的区块:

function foo() {
    var result;

    fetch(url).then(function(response) {
        result = response;
        // return response; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}

当前回答

2017 答案:你现在可以做你想要的事情在每个当前的浏览器和 Node.js

这是相当简单的:

返回承诺 使用“等待”,这将告诉JavaScript等待承诺将被解决到一个值(如HTTP答案) 将“async”关键字添加到主功能

下面是您的代码工作版本:

(async function(){

    var response = await superagent.get('...')
    console.log(response)

})()

等待支持所有当前的浏览器和 Node.js 8

其他回答

您正在使用 Ajax 错误. 想法不是要有它返回任何东西,而是将数据转移到所谓的召回功能,处理数据。

这就是:

function handleData( responseData ) {

    // Do what you want with the data
    console.log(responseData);
}

$.ajax({
    url: "hi.php",
    ...
    success: function ( data, status, XHR ) {
        handleData(data);
    }
});

在提交处理器中返回任何东西不会做任何事情,你必须或者放弃数据,或者直接在成功函数中做你想要的事情。

让我们从一个简单的JavaScript功能开始:

function foo(){
    // Do something
    return 'wohoo';
}

let bar = foo(); // 'bar' is 'wohoo' here

这是一个简单的同步函数呼叫(每个字符串的代码在下一个字符串之前“完成”),结果是相同的预期。

function foo(){
    setTimeout( ()=> {
        return 'wohoo';
   }, 1000)
}

let bar = foo() // 'bar' is undefined here

所以你去那里;那个延迟只是打破了我们所期望的功能!但是发生了什么事? 好吧,如果你看代码,它真的很合乎逻辑。

承诺实际上是关于它意味着什么:它意味着该功能保证你提供它在未来得到的任何产量。

function foo(){
   return new Promise((resolve, reject) => { // I want foo() to PROMISE me something
    setTimeout ( function(){
      // Promise is RESOLVED, when the execution reaches this line of code
       resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'
    }, 1000 )
  })
}

let bar;
foo().then( res => {
    bar = res;
    console.log(bar) // Will print 'wohoo'
});

更新(与 async/await 承诺)

此分類上一篇: Catch Version:

function saveUsers(){
     getUsers()
      .then(users => {
         saveSomewhere(users);
      })
      .catch(err => {
          console.error(err);
       })
 }

async/await 版本:

  async function saveUsers(){
     try{
        let users = await getUsers()
        saveSomewhere(users);
     }
     catch(err){
        console.error(err);
     }
  }

角质1

使用AngularJS的人可以通过承诺来处理这种情况。

這裡說,

承诺可以用于无与伦比的功能,并允许一个连接多个功能。

你也可以在这里找到一个好解释。

下面提到的文档中有一个例子。

  promiseB = promiseA.then(
    function onSuccess(result) {
      return result + 1;
    }
    ,function onError(err) {
      // Handle error
    }
  );

 // promiseB will be resolved immediately after promiseA is resolved
 // and its value will be the result of promiseA incremented by 1.

孔子2及以后

在 Angular 2 中,请参见下面的例子,但建议使用 Angular 2 的观察器。

 search(term: string) {
     return this.http
       .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
       .map((response) => response.json())
       .toPromise();
}

你可以用这种方式,

search() {
    this.searchService.search(this.searchField.value)
      .then((result) => {
    this.result = result.artists.items;
  })
  .catch((error) => console.error(error));
}

但TypeScript不支持本地ES6承诺,如果你想使用它,你可能需要插件。

此外,这里是承诺的规格。

等待

请求以无同步的方式工作,所以你不能像典型代码那样同步阅读数据。 但是,使用 async/await 你可以创建一个与常见的同步/序列风格相似的无同步代码. 处理响应数据的代码必须由一个无同步函数(在下面的剪辑中加载)并在它里面你需要在 foo()(whic)之前添加等待关键字。

async 函数 foo() { var url = 'https://jsonplaceholder.typicode.com/todos/1'; var result = (await fetch(url)).text(); // 或.json() return result; } async 函数 load() { var result = await foo(); console.log(result); } load();

记住,一个无与伦比的功能总是(显而易见)将其结果转化为一个承诺(因此它返回一个承诺)。

使用 async/await 与一个 transpilers 如 Babel 让它工作在较老的浏览器. 你还需要安装这个 Babel 预定和 polyfill 从 npm: npm i -D babel-preset-env babel-polyfill。

function getData(ajaxurl) { 
  return $.ajax({
    url: ajaxurl,
    type: 'GET',
  });
};

async test() {
  try {
    const res = await getData('https://api.icndb.com/jokes/random')
    console.log(res)
  } catch(err) {
    console.log(err);
  }
}

test();

或者.then callback 只是写同样的逻辑的另一种方式。

getData(ajaxurl).then(function(res) {
    console.log(res)
}