简体   繁体   English

如何从变量内部的调用函数获取回调

[英]How to get callback from calling function inside variable

I have some Javascript code that is similar to the following: 我有一些类似于以下代码的Javascript代码:

var Requests = {
  get: function(search) {
    // HTTP request happens, returns data.
  }
}

I'm trying to invoke this somewhere else, like the following: 我试图在其他地方调用它,如下所示:

Requests.get('thing');

Although this is returning undefined because it's not waiting for the http request result. 尽管这返回的是undefined,因为它没有等待http请求的结果。 I'm wondering how I can defer this request until it's successful, or somehow check for a callback in the invoking code. 我想知道如何才能将此请求推迟到成功为止,或者以某种方式检查调用代码中的回调。 Thanks! 谢谢!

You need a promise. 你需要一个承诺。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

var Requests = {
     get: function(search){
        return new Promise(resolve,reject){
           //if it does what you want
           if(data) resolve(data)
           else reject(error)
        }
     }
}

And then 接着

Requests.get('thing').then('do something else')

The other option is to use await/async but that is not fully supported yet. 另一个选项是使用await / async,但尚不完全支持。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

The function can return a promise: 该函数可以返回一个promise:

var Requests = {
  get: function(search) {
    return new Promise(function(resolve, reject){
       // call resolve in case of success, and reject in case of error
    })
  }
}

Requests.get('thing').then(
  function(response){
   // success
  },
  function(error){
   // something went wrong
  }
);

In the "then" method of a Promise object, you need to pass the two functions used when the promise is resolved or rejected. 在Promise对象的“ then”方法中,您需要传递在解决或拒绝Promise时使用的两个函数。

For more information on Promises: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise . 有关Promises的更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM