简体   繁体   English

如何同步多次调用返回承诺的任何函数

[英]How to synchronously call multiple times any function which is returning promise

For example, I have function which Promise.resolve() if I already have any cached entity id else it make ajax call to reserve entity id and then Promise.resolve() new entity id例如,我有函数 which Promise.resolve() 如果我已经有任何缓存的实体 id 否则它会调用 ajax 来保留实体 id 然后 Promise.resolve() 新的实体 id

function getReservedEntityId(collectionName) {
        //if (!haveCachedIds) {
            //make ajax call to reserve new ids
            Promise.resolve(newId);
        }
        return Promise.resolve(cachedId);
};

How can we synchronously call it multiple times to reserve multiple entity ids?我们如何同步多次调用它来保留多个实体 id?

PS I know that the correct approach is to make this function take parameter that will specify the count of entity ids and make request and return ids accordingly but I wanted to understand how can we call synchronously multiple times any function which is returning promise. PS我知道正确的方法是让这个函数接受参数,该参数将指定实体 id 的计数并相应地发出请求和返回 id,但我想了解我们如何多次同步调用任何返回承诺的函数。

First, the implementation of getReservedEntityId() needs to make correct use of promises.首先, getReservedEntityId()的实现需要正确使用promise。 I recommend a thorough reading of how promises work .我建议彻底阅读 Promise 是如何工作的 In particular, it's important to understand that when your function performs an asynchronous task, you need to return a promise that will either resolve or reject based on the result of the asynchronous task.特别是,当您的函数执行异步任务时,您需要返回一个承诺,该承诺将根据异步任务的结果解析或拒绝,了解这一点很重要。

function getReservedEntityId(collectionName) {
  if (haveCachedIds) {
    return Promise.resolve(cachedId);
  } else {
    return new Promise((resolve, reject) => {
      // Make the AJAX call and call resolve(newId) in the success callback
      // or call reject(errCode) in the failure callback.
      // The arguments newId and errCode can be any values you like and are
      // the values that get passed to the next link in the promise chain
      //   i.e. the values passed to then() or catch()
    });
  }
}

With that squared away, there are two recommended ways to make the calls synchronous:考虑到这一点,有两种推荐的方法可以使调用同步:

1) Utilize a promise chain 1)利用承诺链

getReservedEntityId(collectionName)
  .then((id) => {
    // Probably want to do something with `id` first...

    return getReservedEntityId(collectionName);
  })
  .then( ... )
  .then( ... );

Of course, if you're going to pass the same function to each .then() call, you could just as well declare it as a regular function so as to not repeat yourself.当然,如果您要将相同的函数传递给每个.then()调用,您也可以将其声明为常规函数,以免重复。

2) Using async/await 2) 使用异步/等待

This is a new ES2017 feature and is still not widely supported.这是一个新的 ES2017 特性,仍然没有得到广泛支持。 As of the time of this writing, Node.js supports async/await with the --harmony flag, but most browsers do not .在撰写本文时,Node.js 支持带有--harmony标志的 async/await,但大多数浏览器不支持 That said, async/await is intended for this exact purpose, treating functions returning promises as though they were synchronous.也就是说, async/await 正是为此目的而设计的,将返回 promise 的函数视为同步的。 If you want to start using async/await in your code now, it is common practice to use JavaScript transpilers which which transpile your future-ready JavaScript to code that is supported by all major browsers.如果你现在想开始在你的代码中使用 async/await,通常的做法是使用 JavaScript 转译器,它将你的未来就绪 JavaScript 转译为所有主要浏览器都支持的代码。

This is how you would use async/await:这是您使用 async/await 的方式:

(async function someAsyncFunction {
  const id1 = await getReservedEntityId(collectionName);
  const id2 = await getReservedEntityId(collectionName);
  const id3 = await getReservedEntityId(collectionName);
                          .
                          .
                          .
})();

The syntax is much nicer and more readable than the promise chain because it's designed for this exact purpose.语法比承诺链更好,更易读,因为它就是为这个目的而设计的。 Note that I have made the function self-invoking here so that it matches your behavior without having to make an extra function call.请注意,我在此处使函数自调用,以便它与您的行为相匹配,而无需进行额外的函数调用。 But you can use and call a function defined with async function just like any other function that returns a promise.但是您可以使用和调用用async function函数定义的async function ,就像任何其他返回承诺的async function一样。

@fvgs your answer is also correct. @fvgs 你的回答也是正确的。 But here's the complete solution and the challenge which I have faced is to maintain list of reserveIds which was in response of every getReservedEntityId call.但这里是完整的解决方案,我面临的挑战是维护 ReserveIds 列表,这是对每个 getReservedEntityId 调用的响应。

getEntityIds: function (entity, count) {
    if (!count || count == 1)
        return Utils.getReservedEntityId(entity);

    var promise = new Promise(function(resolve, reject) {
        var result = [];
        var chain = Utils.getReservedEntityId(entity);
        var callBack = function CB (result, newId) {
            result.push(newId);

            if (result.length == count)
                resolve(result);
            else
                return Utils.getReservedEntityId(entity);
        }.bind(null, result);

        for (var i=1; i <= count; i++) {
            chain.then(callBack);
        }

        chain.catch(reject);
    });

    return promise;
}

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

相关问题 我如何使用循环多次(同步)调用同一个异步函数? - how can i call the same asynchronous function multiple times (synchronously) using a loop? 如何调用一个根据诺言的结果返回诺言的函数? - How to call a function returning a promise on a result of a promise? 如何在Promise内部调用Promise,在javascript中一次调用2次function - How to call Promise inside Promise and call function 2 times at a time in javascript 如何多次调用一个函数 - How to call a function Multiple times 如何等待不是promise但包含promise的函数的调用结果? - How to await the result of a call to a function which is NOT a promise, but contains a promise? 多次调用一个promise函数,直到另一个promise函数满足条件 - Call a promise function multiple times until condition met from another promise function 如何使用 promise、.then()、.catch() 多次尝试异步函数 - How to attempt an async function multiple times using promise, .then(), .catch() 函数不同步返回值 - Function not returning value synchronously 有没有办法一次在JavaScript中多次调用函数? 使用木偶 - Is there any way to call a function in JavaScript multiple times at once? Using puppeteer 如何多次调用sendToDevice作为函数结果? - How to call sendToDevice multiple times as a function result?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM