相关疑难解决方法(0)

使用async/await和forEach循环

asyncawait循环中使用是否有任何问题?我正在尝试循环遍历文件数组和forEach每个文件的内容.

import fs from 'fs-promise'

async function printFiles () {
  const files = await getFilePaths() // Assume this works fine

  files.forEach(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  })
}

printFiles()
Run Code Online (Sandbox Code Playgroud)

这段代码确实有效,但这可能会出错吗?我有人告诉我你不应该使用await这样的高阶函数,所以我只是想问一下这是否有任何问题.

javascript node.js promise async-await ecmascript-2017

864
推荐指数
24
解决办法
38万
查看次数

在新的Promise()构造函数中使用async/await是一种反模式吗?

我正在使用该async.eachLimit功能一次控制最大操作数.

const { eachLimit } = require("async");

function myFunction() {
 return new Promise(async (resolve, reject) => {
   eachLimit((await getAsyncArray), 500, (item, callback) => {
     // do other things that use native promises.
   }, (error) => {
     if (error) return reject(error);
     // resolve here passing the next value.
   });
 });
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我无法将该myFunction函数声明为异步,因为我无法访问eachLimit函数的第二个回调内的值.

javascript asynchronous node.js async-await

62
推荐指数
3
解决办法
3万
查看次数

由于异步生成器中的非并行等待承诺而导致速度下降

我正在使用生成器和Bluebird编写代码,我有以下内容:

var async = Promise.coroutine;
function Client(request){
    this.request = request;
}


Client.prototype.fetchCommentData = async(function* (user){
    var country = yield countryService.countryFor(user.ip);
    var data = yield api.getCommentDataFor(user.id);
    var notBanned = yield authServer.authenticate(user.id);
    if (!notBanned) throw new AuthenticationError(user.id);
    return {
        country: country,
        comments: data,
        notBanned: true
    };
});
Run Code Online (Sandbox Code Playgroud)

但是,这有点慢,我觉得我的应用程序等待I/O太多而且它不是并行的.如何提高应用程序的性能?

总响应时间为800 countryFor+ 400 getCommentDataFor+ + 600,authenticate因此总共1800ms这是很多.

javascript generator promise async-await bluebird

18
推荐指数
2
解决办法
3312
查看次数

如何将 Promise.all() 限制为每秒 5 个承诺?

我有几个项目需要查询第 3 方 API,并且该 API 的调用限制为每秒 5 次调用。我需要以某种方式将我对 API 的调用限制为每秒最多 5 次调用。

到目前为止,我只使用Promise.all()了一系列 promise,其中每个 promise 向 API 发送一个请求,并在 API 以 HTTP 状态代码响应时进行解析,200并在它以其他状态代码响应时拒绝。但是,当数组中有 5 个以上的项目时,我可能会面临Promise.all()拒绝的风险。

如何将Promise.all()呼叫限制为每秒 5 个呼叫?

javascript throttling node.js promise es6-promise

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

在Promise.race中完成哪些承诺

上下文:我需要进行大量可并行化的异步调用(想想大约300到3000个ajax调用).但是,我不想通过立即调用它们来拉紧浏览器或服务器.我也不想按顺序运行它们,因为它需要很长时间才能完成.我决定一次运行五个左右,并导出此功能:

async function asyncLoop(asyncFns, concurrent = 5) {
    // queue up simultaneous calls 
    let queue = [];
    for (let fn of asyncFns) {
        // fire the async function and add its promise to the queue
        queue.push(fn());
        // if max concurrent, wait for the oldest one to finish
        if (queue.length >= concurrent) {
            await queue.shift();
        }
    }
    // wait for the rest of the calls to finish
    await Promise.all(queue);
};
Run Code Online (Sandbox Code Playgroud)

其中asyncFns是一个可迭代的(尚未调用的)异步函数.

问题:这是有效的,但我发现,最老的是第一个完成的并不总是如此.我想修改函数,以便它使用Promise.race等到第一个promise成功,然后从那里继续.但是,我不知道要删除哪个承诺:

        // if max concurrent, wait for the …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous async-await es6-promise

12
推荐指数
2
解决办法
1815
查看次数

在特定时间打开承诺的承诺金额

以下Typescript一次执行一个调用doSomething(action).(这意味着列表中的第二项在第一项完成之前不会进行调用).

async performActionsOneAtATime() {
    for (let action of listOfActions) {
        const actionResult = await doSomethingOnServer(action);
        console.log(`Action Done: ${actionResult}`);
    }
 }
Run Code Online (Sandbox Code Playgroud)

这个会立即将所有请求发送到服务器(无需等待任何响应):

async performActionsInParallel() {
    for (let action of listOfActions) {
        const actionResultPromise = doSomething(action);
        actionResultPromise.then((actionResult) => {
            console.log(`Action Done: ${actionResult}`);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但我真正需要的是一种限制它们的方法.也许一次打开10或20个电话.(一次一个太慢,但所有600都会使服务器超载.)

但我很难搞清楚这一点.

关于如何限制每次打开X的调用次数的任何建议?

(这个问题使用TypeScript,但我对ES6 JavaScript答案没问题.)

javascript throttling promise typescript

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

限制正在运行的承诺的并发性

我正在寻找一个promise函数包装器,它可以在给定的promise运行时限制/限制,以便在给定的时间只运行一定数量的promise.

在下面的情况下delayPromise,永远不应该同时运行,它们应该以先来先服务的顺序一次运行一个.

import Promise from 'bluebird'

function _delayPromise (seconds, str) {
  console.log(str)
  return Promise.delay(seconds)
}

let delayPromise = limitConcurrency(_delayPromise, 1)

async function a() {
  await delayPromise(100, "a:a")
  await delayPromise(100, "a:b")
  await delayPromise(100, "a:c")
}

async function b() {
  await delayPromise(100, "b:a")
  await delayPromise(100, "b:b")
  await delayPromise(100, "b:c")
}

a().then(() => console.log('done'))

b().then(() => console.log('done'))
Run Code Online (Sandbox Code Playgroud)

关于如何获得像这样的队列设置的任何想法?

我有精彩的"去抖"功能Benjamin Gruenbaum.我需要修改它来根据它自己的执行而不是延迟来限制一个承诺.

export function promiseDebounce (fn, delay, count) {
  let working = 0
  let queue = []
  function work () { …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise bluebird

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

可以从承诺数组中删除承诺吗?

我想创建类似处理同步行为和异步行为的东西。例如,我希望能够像这样:

function timeout(myJson) {
    return new Promise(function (resolve, reject) {
        setTimeout(resolve, myJson.wait, myJson);
    });
}

async function funct() {
    try {
        let PromiseTolaunch = [{ "wait": 10, "nextIndex": 2, "id": 1 }, 
                                { "wait": 500, "nextIndex": -1, "id": 2 }, 
                                { "wait": 5, "nextIndex": -1, "id": 3 }];
        let launchedPromise = [], finishedPromise;

        launchedPromise.push(timeout(PromiseTolaunch[0]));
        launchedPromise[0].id = PromiseTolaunch[0].id;
        launchedPromise.push(timeout(PromiseTolaunch[1]));
        launchedPromise[1].id = PromiseTolaunch[1].id;
        while (launchedPromise.length !== 0) {
            finishedPromise = await Promise.race(launchedPromise);
        [*] console.log(finishedPromise); // Expected output: { "wait": 10, "nextIndex": 2 …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise

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

在Javascript中与缓冲池大小同时执行promises

我有一个带有promise的函数,每次都必须使用不同的params执行n次.我想以一种方式链接承诺,即脚本当时总是处理3-4个承诺.

我用promise.all做了它,它同时执行3个,当所有的promises结算时,它继续下一个3.

如何使其工作,当3中的一个解决它立即与另一个开始,但总是在当时最大3工作?

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

    if( i > 0 && i%3 == 0 ){

      await Promise.all([
       doTaskFunction(tasks[i]),
        doTaskFunction(tasks[i-1]),
        doTaskFunction(tasks[i-2]),
      ]);
    }

  }
Run Code Online (Sandbox Code Playgroud)

javascript concurrency node.js promise

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

带有等待功能的 JavaScript 简单任务运行程序

我想实现类似任务运行程序的东西,它将被推送新任务。这些任务中的每一个都可以是一些异步操作,例如等待用户或进行 API 调用或其他操作。任务运行程序确保一次只能执行允许数量的任务,而其他任务将继续等待,直到轮到它们。

class Runner {
  constructor(concurrent) {
    this.taskQueue = []; //this should have "concurrent" number of tasks running at any given time

  }

  push(task) {
    /* pushes to the queue and then runs the whole queue */
  }
}
Run Code Online (Sandbox Code Playgroud)

调用模式是

let runner = new Runner(3);
runner.push(task1);
runner.push(task2);
runner.push(task3);
runner.push(task4);
Run Code Online (Sandbox Code Playgroud)

其中任务是一个函数引用,它将在最后运行一个回调,我们可以知道它已完成。所以它应该像

let task = function(callback) {
  /* does something which is waiting on IO or network or something else*/
  callback(); 
}
Run Code Online (Sandbox Code Playgroud)

所以我正在推动跑步者的关闭,比如

runner.push(function(){return task(callback);});
Run Code Online (Sandbox Code Playgroud)

我想我可能还需要添加一个 waitList 队列。但任务本身并不是承诺,所以我不知道如何检查这些任务是否完成。

无论如何,我需要正确的方法。

javascript async-await ecmascript-6 es6-promise

5
推荐指数
2
解决办法
4441
查看次数