相关疑难解决方法(0)

多次调用异步函数

所以我有一个方法,我想在一个循环中多次调用。这是功能:

function PageSpeedCall(callback) {
    var pagespeedCall = `https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=https://${websites[0]}&strategy=mobile&key=${keys.pageSpeed}`;
    // second call
    var results = '';
    https.get(pagespeedCall, resource => {
        resource.setEncoding('utf8');
        resource.on('data', data => {
            results += data;
        });
        resource.on('end', () => {
            callback(null, results);
        });
        resource.on('error', err => {
            callback(err);
        });
    });
    // callback(null, );
}
Run Code Online (Sandbox Code Playgroud)

如您所见,这是一个调用PageSpeed API的异步函数。然后,由于,它获得了响应callback并将其呈现在视图中。现在如何使它在for / while循环中起作用?例如

function PageSpeedCall(websites, i, callback) {
    var pagespeedCall = `https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=https://${websites[i]}&strategy=mobile&key=${keys.pageSpeed}`;
    // second call
    var results = '';
    https.get(pagespeedCall, resource => {
        resource.setEncoding('utf8');
        resource.on('data', data => {
            results += data; …
Run Code Online (Sandbox Code Playgroud)

javascript node.js express

1
推荐指数
1
解决办法
2623
查看次数

为什么 Promise.all 的错误?:TypeError:无法读取未定义的属性“Symbol(Symbol.iterator)”

我有以下控制器方法:

const org = await organisation.toJSON().name;
// The next line works fine, that's not the problem
const users = await organisation.getUsers(organisation.toJSON().id, User);
await Promise.all(users.forEach(async user => {
  await sendAccountEmail(
    user.email,
    user.surname,
    org
  );
}));
Run Code Online (Sandbox Code Playgroud)

对于该Promise行,我收到一个错误:

UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“Symbol(Symbol.iterator)”

知道我的代码有什么问题吗?

javascript node.js

1
推荐指数
1
解决办法
3493
查看次数

为什么 Array.prototype.forEach() 不能像 for 循环一样识别异步函数中的 await?

使用awaitfor一个内循环async函数提供所述执行等待当前完成的预期结果Promise的迭代中

const story = [1,2,3,4,5];

(async() => {

  for (var i = 0; i < story.length; i++) {
    await new Promise(function(resolve) {
      setTimeout(function() {
        resolve(story[i])
      }, 1000)
    }).then(function(chapter) {
      document.body
        .appendChild(document.createTextNode(chapter));
    });
  }

})()
Run Code Online (Sandbox Code Playgroud)

为什么在传递给的回调中使用时Array.prototype.forEach()不提供等待当前完成的相同功能?Promiseawait.forEach()

const story = [1,2,3,4,5];

(async() => {

  story.forEach(async function(chapterUrl) {
    // does not await for Promise fulfillment
    await new Promise(function(resolve) {
      setTimeout(function() {
        resolve(chapterUrl)
      }, 1000)
    }).then(function(chapter) {
      document.body
      .appendChild(document.createTextNode(chapter));
    });
  }); …
Run Code Online (Sandbox Code Playgroud)

javascript async-await ecmascript-6

0
推荐指数
1
解决办法
352
查看次数

使用 forEach 和 axios 进行异步/等待

我遇到了一个问题,需要你的帮助。我需要在名为 rudder 的软件中使用自动注册服务器的 API。为了达到我的目标,我必须使用 2 个 http 请求:

  1. (GET) 获取所有处于挂起状态的服务器
  2. (POST)注册我的服务器

我的第一个请求得到了完美处理,但我不知道如何实现第二个请求。

这是我的代码(/src/controllers/registration.js):

async function index(req, res) {
  // Check parameter
  if (!req.body.hostname) {
    return res.status(422).json({ result: 'error', message: 'Missing hostname parameter' });
  }

  try {
    const pendingNodes = await axios.get(`${config.rudderURL}/rudder/api/latest/nodes/pending?include=minimal`, { headers });
    Object.keys(pendingNodes.data.data.nodes).forEach((key) => {
      // Search in all pending machine if our node is present
      const node = pendingNodes.data.data.nodes[key];
      if (req.body.hostname === node.hostname) {
        // Registration
        const response = async axios.get(`${config.rudderURL}/rudder/api/nodes/pending/${node.id}`, { headers });
        // console.log(response);
        return …
Run Code Online (Sandbox Code Playgroud)

javascript node.js async-await axios

0
推荐指数
1
解决办法
1万
查看次数

如何在forEach中逐个运行Promise

我试图在每个人的内部逐个履行承诺.

对不起,我知道这可能是一个简单的问题,但我发现很难找到如何解决这个问题的答案.

我希望console.log会像这样显示

test
a
test
b
test
c
Run Code Online (Sandbox Code Playgroud)

但是,它显示这样

test
test
test
a
b
c
Run Code Online (Sandbox Code Playgroud)

这是我的代码 https://jsfiddle.net/brianivander/b6csvrn9/1/

var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
  promise().then(() => {
    console.log(element);
  })
});

function promise() {
  return new Promise((resolve, reject) => {
    console.log('test');
    resolve()
  })
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

javascript promise

0
推荐指数
1
解决办法
77
查看次数

Await function never executes

I have this function, that iterates through an array of strings, where each string represents a user's UID. The function is supposed to go to each user's profile, check for their most current reputation (same like SO), and then push a map of uid and reputation to a new array.

The second array always came out empty so I've placed a few logs to check what is happening. This is my function:

candidates.forEach(async id => {
  console.log('user log ' + …
Run Code Online (Sandbox Code Playgroud)

node.js firebase typescript google-cloud-functions google-cloud-firestore

0
推荐指数
1
解决办法
44
查看次数

async 和 await 无法正常工作 JavaScript

我正在尝试在我的 react js 应用程序上使用 async 和 await。但它不能正常工作。

const handleFinish = async () => {
    const startDateString = startDate.format('YYYY-MM-DDThh:mm');
    const endDateString = endDate.format('YYYY-MM-DDThh:mm');
    const createdString = moment().format('YYYY-MM-DDThh:mm');
    const requestData = [];
    const previousData = [];
    selectedCustomerData.forEach(customer => {
      selectedProductData.forEach(product => {
        previousData.push({
          customer: customer,
          product: product
        });
      });
    });
    await previousData.forEach(async element => {
      const tempStartDate = moment().add(element.customer.leadtime, 'days');
      const apiUrl = '/productprice/?customerid=' + element.customer.customerid + 
                      '&productkey=' + element.product.productkey + 
                      '&isrulendNull=true';
      await api.get(apiUrl).then(response => {
        let newPrice = 0;
        if (priceMethod …
Run Code Online (Sandbox Code Playgroud)

javascript arrays asynchronous async-await reactjs

0
推荐指数
1
解决办法
88
查看次数

如何在 forEach 循环内调用 async-await API 调用?

我正在执行一项任务,需要一项一项更新待办事项列表。我正在选择一个待办事项列表,当我单击更新按钮时,它应该使用 forEach 循环逐个更新待办事项。如果选择待办事项,下面是列表

selectedTodos = [
{
todoID:630316783e09e69bda667e2e,
userID:630316783e09e69bda63dvft3,
completed:false
},
{
todoID:630316783e09e69bda667ssdw36,
userID:988765yk6783e09e69bda667e2e,
completed:false
},
{
todoID:630316783765gbjybda667e2e,
userID:630316783e09e69vfft567742,
completed:false
},
]
Run Code Online (Sandbox Code Playgroud)

我正在使用forEach循环来迭代列表并逐一更新,如下所示

selectedTodos.forEach(async(todo)=>{

const {data} = await axios.put(API_URL+"/todo/"+ todo.todoID,{
completed:true
})
console.log(data)
})
Run Code Online (Sandbox Code Playgroud)

这里的 async-await 不在循环内工作,但是当我单独更新它时,它正在工作。它不仅仅在forEach循环上工作。我没有一个端点可以一次更新所有内容。我需要循环遍历列表并一一更新。还有其他办法吗?

javascript arrays async-await reactjs react-hooks

0
推荐指数
1
解决办法
1万
查看次数

异步循环不返回值

我有一个异步循环来检查数组,如果找到特定值,它会循环另一个数组以匹配找到的值。

所以我的第一个实现。我打开一个异步循环并从数据库获取数据

mergedObject = [];
 array1.forEach(async (item) => {
  if (item.id == 'XXX') {
   const dbInfo = await readDB();
Run Code Online (Sandbox Code Playgroud)

数据库信息,我想推入一个数组并构建一个 json 对象。

      dbInfo.forEach(async (itemDB) => {
    object.push({
      id,
      name,
      ..
      ..
Run Code Online (Sandbox Code Playgroud)

在循环结束时,我将新对象与“旧”对象合并

  mergedObject = _.map(oldObject, (objs) => {
    _.assign(objs, _.find(object, {
      id: objs.id,
    }));
  });
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,在 forEach 内我正确地获取了日志。但是如果我想在 forEach (array1) 之外使用 mergedObject 我得到log: []

这是我第一次尝试异步。我之前使用过回调。如何访问 forEach 之外的 mergedObject?

node.js async-await

-1
推荐指数
1
解决办法
1147
查看次数