简体   繁体   English

Javascript,来自嵌套Promises的全局变量分配

[英]Javascript, global variable assignment from nested Promises

I have method that resolves a promise that retrieves some Products 我有一种方法可以解决可检索某些产品的承诺

global.getProducts().then(function (prodPromised) {

For each prodPromised I have a Category ID but I also want the Category Name. 对于每个prodPromised,我都有一个类别ID,但我也想要类别名称。 So, I create an array of promises in which I assing the Category Name to each Product. 因此,我创建了一个promise数组,在其中将类别名称分配给每个产品。

var products = [];

for (var i = 0; i < prodPromised.length; i++) {
    promises.push(self.createCatName(prodPromised[i]));
}

After that I resolve the promises ... 在那之后,我履行了诺言...

Promise.all(promises).then((products) => {

... I loop them for some operations ...我循环执行一些操作

for (var i = 0; i < products.length; i++) {

The problem is that I'd like to store the array products in a "upper" position so to use it for another method. 问题是我想将阵列产品存储在“上部”位置,以便将其用于另一种方法。

I suppose there's something related to the hoisting, but I dont' understand how to do it :-( 我想这与起重有关,但是我不知道该怎么做:-(

Thanks 谢谢

You can either create a variable that you assign the promises to. 您可以创建一个变量,将其分配给诺言。 Keep in mind that you have to continue with async code! 请记住,您必须继续执行异步代码!

let products = null;
global
    .getProducts()
    .then(function (prodPromised) {
        products = prodPromised;
    })

This wont work: 这将无法工作:

let products = null;
global
    .getProducts()
    .then(function (prodPromised) {
        products = prodPromised;
    });
products.forEach( function( product ) {
    // do stuff
} );

But this should: 但这应该:

let products = null;
global
    .getProducts()
    .then(function (prodPromised) {
        products = prodPromised;
    })
    .then(function() {
        products.forEach( function( product ) {
            // do stuff
        } );
    });

Or alternatively, and this is my own preferred solution, because you don't have to make a variable for it outside the scope. 或者,这是我自己的首选解决方案,因为您不必在范围之外为其创建变量。 Anything you return from a .then() callback, will be available in the next: .then()回调返回的所有内容都将在接下来的内容中提供:

global
    .getProducts()
    .then(function (prodPromised) {
        // do first stuff
        return prodPromised;
    })
    .then(function (prodPromised) {
        // do second stuff.
    });

If createCatName is a synchronous function you can do the following 如果createCatName是同步函数,则可以执行以下操作

const products = global.getProducts().then(
  products=>
    products.map(self.createCatName)
);

If createCatName is an asynchronous function you do do this 如果createCatName是异步函数,则可以执行此操作

const products = global.getProducts().then(
  products=>
    Promise.all(
      products.map(self.createCatName)
    )
);

when you want to use products then you can use the promise of products like so: 当您想使用产品时,可以使用产品承诺:

products.then(
  products=>{
    //use products here
  }
).catch(
  err=>console.warn("Something went wrong getting products:",err)
);

The value products is not an actual list of products but a list of products that may or may not be available in the future (it may not if there was an error). 有价产品不是实际的产品列表,而是将来可能会或可能不会提供的产品列表(如果出现错误,则可能不会)。

So if you want to access products you always have to access it as a promise, you can use async await syntax but if you don't know what a promise is then please learn that first. 因此,如果您要访问产品,则始终必须作为承诺来访问它,可以使用async await语法,但是如果您不知道承诺是什么,请首先学习该内容。

Async functions have await but actually return a promise immediately so anything outside the async function is handed a promise immediately and does not get the awaited result. 异步函数已经处于等待状态,但是实际上实际上立即返回了一个Promise,因此异步函数之外的任何东西都会立即被传递给Promise,而不会得到等待的结果。

More on why and how on promises can be found here . 更多关于为什么以及如何实现承诺的信息可以在这里找到。

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

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