相关疑难解决方法(0)

什么是明确的承诺构建反模式,我该如何避免它?

我编写的代码看起来像:

function getStuffDone(param) {           | function getStuffDone(param) {
    var d = Q.defer(); /* or $q.defer */ |     return new Promise(function(resolve, reject) {
    // or = new $.Deferred() etc.        |     // using a promise constructor
    myPromiseFn(param+1)                 |         myPromiseFn(param+1)
    .then(function(val) { /* or .done */ |         .then(function(val) {
        d.resolve(val);                  |             resolve(val);
    }).catch(function(err) { /* .fail */ |         }).catch(function(err) {
        d.reject(err);                   |             reject(err);
    });                                  |         });
    return d.promise; /* or promise() */ |     });
}                                        | }
Run Code Online (Sandbox Code Playgroud)

有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …

javascript promise q bluebird es6-promise

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

如何等到元素存在?

我正在研究Chrome中的扩展程序,我想知道:什么是找出元素何时出现的最佳方法?使用普通的javascript,检查直到元素存在的间隔,或jQuery有一些简单的方法来做到这一点?

javascript jquery google-chrome google-chrome-extension

213
推荐指数
17
解决办法
22万
查看次数

在承诺中使用等待

将Promise的回调定义为异步似乎存在一些固有的错误:

return new Promise(async (resolve, reject) => {
  const value = await somethingAsynchronous();
  if (value === something) {
    return resolve('It worked!');
  } else {
    return reject('Nope. Try again.');
  }
});
Run Code Online (Sandbox Code Playgroud)

这显然是一个反模式,并且可能会产生编码问题.我理解,即使awaittry/ catch块中放置语句,也很容易在此处捕获错误.

我的第一个问题是,当一个人想要转发具有不同解析/拒绝值的Promise时,最好的方法是什么?用then/catch?即

return new Promise((resolve, reject) => {
  somethingAsynchronous().then(value => {
    if (value === something) {
      return resolve('It worked!');
    } else {
      return reject('Nope. Try again.');
    }
  }); // errors would now be propagated up
});
Run Code Online (Sandbox Code Playgroud)

或者你只是按照这里的 …

javascript asynchronous promise async-await ecmascript-6

10
推荐指数
2
解决办法
9945
查看次数

使用 Promise.all 时承诺之间的延迟

有没有办法使用 Promise.all() 延迟对一系列承诺的评估?

在将它们添加到数组之前手动将延迟函数添加到每个承诺的末尾是否有意义?

Promise.all([p1,p2,p3]).then(res => console.log(res))
Run Code Online (Sandbox Code Playgroud)

我想添加一个延迟,因为我的服务器无法一次处理太多请求。

promise ecmascript-6

9
推荐指数
4
解决办法
6619
查看次数

与Typescript/ES7中的async/await有限的并行性

我一直在尝试使用Typescript,但我现在对如何有效地使用async/await感到困惑.

我正在将一堆记录插入到数据库中,我需要获取每个插入返回的ID列表.以下简化示例通常起作用,但它并不像我想的那么优雅,而且完全是顺序的.

async function generatePersons() {
    const names = generateNames(firstNames, lastNames);
    let ids = []
    for (let name of names) {
        const id = await db("persons").insert({
            first_name: name.firstName,
            last_name: name.lastName,
        }).returning('id');
        ids.push(id[0])
    }
    return ids
}
Run Code Online (Sandbox Code Playgroud)

我试图用来map避免ids手动创建列表,但我可以让它工作.

我还想拥有的是有限的并行性.所以我的异步调用应该并行发生,直到某个限制,例如,我只想要有10个开放请求,但不是更多.

在Typescript或Javascript ES7中使用async/await实现这种有限的并行性是否有一种相当优雅的方式?或者我是否试图让这个功能做一些不适合的事情?

PS:我知道有数据库的批量插入方法,这个例子有点人为,因为我可以使用它来解决这个特定的问题.但它让我想知道我没有预定义批量方法的一般情况,例如网络请求

javascript async-await typescript

7
推荐指数
2
解决办法
1617
查看次数

JavaScript Promises 混淆反模式?

我花了一整天的时间试图弄清楚我错误地使用了 Promise 的天气。

那是反模式吗?

export const myExample = (payload) => {
  return new Promise((resolve, reject) => {})
}
Run Code Online (Sandbox Code Playgroud)

我可以像这样在承诺中使用异步吗?

export const myExample = (payload) => {
  return new Promise(async (resolve, reject) => {})
}
Run Code Online (Sandbox Code Playgroud)

这也是错的吗?假设添加 async 使其成为默认的承诺,

export const myExample = async (payload) => {
  return new Promise((resolve, reject) => {})
}
Run Code Online (Sandbox Code Playgroud)

如果是这种情况,我是否应该只从与解析相同的函数返回,如果我抛出错误将被拒绝,所以它看起来像那样?

export const myExample = async (payload) => {
  if(payload) return true
  else throw new Error('Promise rejection?')
}
Run Code Online (Sandbox Code Playgroud)

那么 first 和 last 是一样的吗?

javascript promise

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

仅当 'module' 选项设置为 'esnext' 时才允许使用顶级 'await' 表达式

我正在执行 Stripes 集成步骤,但遇到了在步骤 2.1 中发现的代码错误(https://stripe.com/docs/connect/collect-then-transfer-guide#create-an-account-link

我该如何解决这个错误?

代码:

const stripe = require('stripe')('someID');
const account = await stripe.accounts.create({
  type: 'express',
});
Run Code Online (Sandbox Code Playgroud)

错误:

仅当 'module' 选项设置为 'esnext' 或 'system',并且 'target' 选项设置为 'es2017' 或更高版本时,才允许使用顶级 'await' 表达式。 ts(1378)

javascript node.js node-modules stripe-payments

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

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

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

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
查看次数

等待 Promise.all 中的 array.map 迭代

我有以下代码,应该为客户添加项目(如果它们尚不存在)。执行应该是并行的。

await Promise.all(
    customers.map(async (customer) => {
        return customer.items.map(async (item) => {
            return new Promise(async (resolve) => {
                const productExists = someArray.some(
                    (arrayValue) => arrayValue === item.id
                );
                if (!productExists) {
                    logger.info(
                    `customer item ${item.id} does not exist, creating...`
                    );
                    await createCustomerItem(item.id);
                    logger.info(`customer item ${item.id} created.`);

                    someArray.push(item.id);
                } else {
                    logger.info(`customer item ${item.id} already exists, skipping...`);
                }
                resolve(true);
            });
        });
    })

);

logger.info(`All items should now be present`);
Run Code Online (Sandbox Code Playgroud)

问题是createCustomerItem在以下情况下执行不会等待解决!productExists)

这是日志

customer item 32310 does not exist, creating... …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous node.js promise

6
推荐指数
2
解决办法
4万
查看次数

是否可以将异步函数传递给 setImmediate 以异步调用任意函数?

我想异步调用给定的函数。包装函数 tryCallAsync 是执行此操作的一种方法。这种方法有效。但是,它要求 setImmediate 的回调是异步函数。这似乎是错误的,因为回调返回了一个未使用的 Promise。为此目的将异步函数传递给 setImmediate 是否错误?

async function tryCallAsync(fn, ...args) {

    return new Promise((r, j) => {

        setImmediate(async () => {

            try {
                r(await fn(...args));
            }
            catch (e) {
                j(e);
            }
        })
    })
}

//  Using tryCallAsync

let resolveAsync = tryCallAsync(()=>{
    return new Promise((r,j)=>{
        setImmediate(()=>r('resolveAsync'));
    });
})

resolveAsync.then((resolve)=>console.log(resolve));

let resolve = tryCallAsync(()=>{
    return 'resolve';
});

resolve.then((resolve)=>console.log(resolve));
Run Code Online (Sandbox Code Playgroud)

注意:https://www.youtube.com/watch? v=e3Nh350b6S4

node.js promise

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