如何等待将值添加到数组?

雅各布

我有一个项目,其中我使用Request-Promise和Cheerio解析快餐菜单,然后根据用户的要求返回“订单”。但是,在输出作为数组存储的“订单”时遇到一些麻烦。

var rp = require('request-promise');
var cheerio = require('cheerio');
var tempMenu = [];
var order = [];

function getItem(item) {

    var itemUrl = baseURL + '/' + item

    var itemMenu = {
        uri: itemUrl,
        transform: function (body) {
            return cheerio.load(body);
        }
    };

    rp(itemMenu)
        .then(function ($) {          
            //.class #id tag
            $(".product-card .product-name a").each(function () {
                tempMenu.push($(this).text());
                order.push(tempMenu[Math.floor(Math.random() * tempMenu.length)]);
                
            });
            console.log(order)
        })

        .catch(function (err) {
        }); 
}

getItem('drinks')
console.log(order)

当前,输出为:

[]
[
 'drink1',
 'drink2',
 'drink3'
]

如果我将代码更改为以下内容:

  rp(itemMenu)
        .then(function ($) {          
            //.class #id tag
            $(".product-card .product-name a").each(function () {
                tempMenu.push($(this).text());
                order.push(tempMenu[Math.floor(Math.random() * tempMenu.length)]);
                
            });
            console.log(1)
        })

        .catch(function (err) {
        }); 
}

getItem('drinks')
console.log(2)

日志是

2
1

所以我知道我的问题是当我尝试输出“ order”数组时未填充它,因为它首先被记录了,我的问题是如何等待数组被填充然后输出?

丹吉格

您的getItem函数应该返回a Promise,然后您可以使用其Promise.prototype.then()方法或await关键字来确保在尝试处理结果之前先等待结果。

这是带有一些虚假rp函数和数据的简单示例

// Fake:
const rp = (item) => {
  console.log(`Fetching ${ item }...`);
  
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(Math.random());
    }, 1000 + Math.random() * 2000)
  });
}

function getItem(item) {
  const order = [];
  
  // This `getItem` function returns a Promise...
  return rp(item).then((randomNumber) => {          
    for (let i = 0; i < 10; ++i) {
      order.push(`${ item } ${ randomNumber + i }`);
    }
    
    // ...and when this Promise resolves, it will return the `order`
    // array with the right values in it:
    return order;
  });
}

getItem('Drinks').then(order => console.log(order));

console.log('This is executed after calling getItem, but we ware still waiting for the Promise to resolve...');
.as-console-wrapper {
  max-height: none !important;
}

另一种选择async/await

// Fake:
const rp = (item) => {
  console.log(`Fetching ${ item }...`);
  
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(Math.random());
    }, 1000 + Math.random() * 2000)
  });
}

function getItem(item) {
  const order = [];
  
  // This `getItem` function returns a Promise...
  return rp(item).then((randomNumber) => {          
    for (let i = 0; i < 10; ++i) {
      order.push(`${ item } ${ randomNumber + i }`);
    }
    
    // ...and when this Promise resolves, it will return the `order`
    // array with the right values in it:
    return order;
  });
}

// You can't use `await` outside an `async` function, so we define this first...:
async function loadDataWithAwait() {
  const order = await getItem('Food');

  console.log('This won\'t be executed until getItem\'s Promise is resolved:');
  console.log(order);
}

// ...and now call it:
loadDataWithAwait();
.as-console-wrapper {
  max-height: none !important;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何等待将文件添加到Applescript中的iTunes

来自分类Dev

如何查看整个文件,又如何等待将更多数据添加到该文件?

来自分类Dev

如何将子值添加到新数组?

来自分类Dev

如何将值添加到多数组?

来自分类Dev

如何将值添加到数组

来自分类Dev

如何将元组值添加到Swift数组?

来自分类Dev

如何使用JavaScript将值随机添加到数组

来自分类Dev

如何将值添加到数组列表中

来自分类Dev

如何使用解构将数组值添加到对象?

来自分类Dev

如何将多个值添加到对象数组

来自分类Dev

如何使用JavaScript将值随机添加到数组

来自分类Dev

如何将值添加到多维数组?

来自分类Dev

将值添加到对象数组

来自分类Dev

将数组值添加到ArrayList

来自分类Dev

将值添加到json数组

来自分类Dev

Javascript for() 将值添加到数组

来自分类Dev

将数组中的数组值添加到数组值

来自分类Dev

如何添加到数组中的值

来自分类Dev

如何将动态添加的输入框的值添加到数组中?

来自分类Dev

如何将数组的值添加到ArrayList中而不是该数组的位置?

来自分类Dev

如何将重复键的值添加到键中:[值数组] 在 Perl 中

来自分类Dev

如何仅将非空数组添加到数组?

来自分类Dev

如何将数组添加到数组

来自分类Dev

如何将项目添加到数组列表的数组

来自分类Dev

Swift:如何将字典数组添加到数组?

来自分类Dev

如何将数组添加到多维数组?

来自分类Dev

如何将项目添加到数组列表的数组

来自分类Dev

javascript - 如何将数组添加到数组位置

来自分类Dev

如何将多个HTML表单的值添加到一个数组以发送