相关疑难解决方法(0)

Javascript然后没有承诺返回val

也许我没有正确使用谷歌搜索。没有参数的 then 函数不会阻塞吗?例如,你有一个承诺:

someFunc = () => {
  return new Promise((res,rej)=>{
   somethingAsync(input).then((val) => res(val))
  })
}
Run Code Online (Sandbox Code Playgroud)

在我们功能的以下实现中。两者都会等待 someFunc 返回值吗?

someFunc().then(dosomethingafter())
someFunc().then((val) => dosomethingafter())
Run Code Online (Sandbox Code Playgroud)

javascript promise ecmascript-6 es6-promise

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

理解显式承诺构造反模式

上一篇文章中强调的某些性能建议我参考stackoverflow 中的以下问题避免显式的 Promise 构造反模式

坦白说,我对 JS 和 Node 都是新手,也没有经常使用 Promise。我去读了那些文章,但要么我无法理解或无法联系,要么我对承诺的理解一直模糊/错误

所以我决定在新线程中提出这个问题并寻求帮助。

那么我在做什么以及为什么这样做

我正在创建帮助程序/通用函数,我可以用它来保持代码整洁,如果我想随时更改函数内部的任何内容,我不必手动更改每个函数。

这些是我制作的功能

//Find user by email Address 
const findUserByEmail = (emailAddress) => {
    return new Promise((resolve, reject) => {
     User.findOne({email: emailAddress}).then(response => {
        resolve(res)
      }).catch(error => {
        reject("Error in findUserByEmail", error);
      })
    })
}

//Create User 
const createNewUser = (newUserDetails) => {
    return new Promise((resolve, reject) => {
      new User({
         fullName: newUserDetails.fullName,
         email: newUserDetails.email,
         image: newUserDetails.image,
         gender: newUserDetails.gender,
         age: newUserDetails.age
      }).save().then((response) => { …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose node.js promise

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

节点:使用 promise.all() 并行调用 API?

我有点困惑 promise.all 是如何工作的,它是否并行运行 promise 数组?

所以这是一个示例代码

// index.js

const getSomething = async (args) => {
  return await apiCallHere(args)
}

// Create Array of Promises
const arrayOfPromises = sampleArray.map(sample => new Promise((resolve, reject) => {
      try {
        const something = this.getSomething(sample, args)
        resolve(something) 
      } catch (error) {
        reject(error)
      }
}))

await Promise.all(arrayOfPromises)

Run Code Online (Sandbox Code Playgroud)

据我观察, Promise.all 并行运行承诺,并等待所有承诺完成。

javascript node.js promise

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

等待承诺 - 代码挂起

我第一次使用Javascript Promises并遇到了一些我不理解的东西.

我想要做的是创建一个验证阶段,它运行并检查事情 - 最终等待所有承诺解决.

为此,我创建了一个验证承诺:

 validate = function(data) {
     var p = new Promise(function(resolve, reject)){
Run Code Online (Sandbox Code Playgroud)

在这里,我为所有不同的事情定义一个promises数组:

         var all_promises = Array();
Run Code Online (Sandbox Code Playgroud)

现在做这样的Sequelize调用,同时将promises添加到这个数组中(Sequelize返回promises):

         all_promises.push(resBooking);
         resBooking.count(...).then(...).catch(...);
Run Code Online (Sandbox Code Playgroud)

我有记录声明,证明我们已经通过,一切都很花哨.现在我需要做的就是等待!

        Promise.all(all_promises).then(function(){
            p.resolve();
        });
Run Code Online (Sandbox Code Playgroud)

但这个愚蠢的事情仍然悬而未决 - 等待一些事情要完成.没有CPU使用率.我究竟做错了什么?

javascript node.js promise

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

如何使用ecmascript-6和fetch api获取自定义服务器端错误消息?

当客户端提取请求导致服务器端出错时,我想返回错误代码(400)和自定义消息.我不知道如何使用fetch和promises优雅地在客户端检索这两者.

return fetch('/api/something')
    .then(response => response.json())
    .then(json => {
         console.log(json.message)
        // I only have access to the json here.
        // I'd also like to get the response status code 
        // (from the response object) and potentially 
        // throw an error complete with the custom message.
    })
    .catch(function(ex) {
        console.log('Unhandled Error! ', ex);
    });
Run Code Online (Sandbox Code Playgroud)

谢谢!

fetch ecmascript-6 es6-promise

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

将很多(> 40,000)原生承诺链接在一起会占用太多内存

我有一个项目,我需要编写一个函数来顺序计算几个东西,然后将结果写入SQL DB.不幸的是,我需要重复这个超过40,000次.我使用node.js并承诺完成此任务,但是在10,000次左右的计算之后程序刚刚死亡的内存使用量几乎达到2GB.我开发了自己的本机promiseEach函数,该函数以数量方式获取数组项并使用promises链接它.

我在这里做错了什么?:

function promiseEach(array,promiseFn){
    return new Promise(function(resolve,reject){
        try {
            var promiseArray = [];
            var json = { array: array, counter: 0 }
            for (var i = 0; i < array.length; i++) { 
                promiseArray.push(promiseFn) 
            }
            promiseArray.reduce(function(preFn,curFn,index,pArray){
                return  preFn
                .then( function(z){ return json.array[json.counter++] })
                .then(curFn)
            }, 
            Promise.resolve(json.array[json.counter]))
            .then(resolve,reject)

        }catch(err){
            console.log("promiseEach ERROR:");
            reject(err)
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise

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

在promise中等待异步函数

以下情况:

function myFunction() {

      return new Promise(function (resolve, reject) {

          doSomething();
          let myVariable = doSomethingElse();

          let otherVariable = doOtherThings(myVariable);              

          return resolve(otherVariable);
      });
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望myVariable不是通过函数调用初始化,而是在回调中,或者更确切地说,在.then异步函数返回的promise中.

function myFunction() {

      return new Promise(function (resolve, reject) {

          doSomething();
          let myVariable;

          asynchronousFunctionThatReturnsPromise().then(function(param) {
             myVariable = doSomethingElse(param);
          });

          let otherVariable = doOtherThings(myVariable);              

          return resolve(otherVariable);
      });
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,外部函数会等到myVariable被赋值,直到它执行doOtherThings(myVariable),但我想这在javascript中是不可能的.

不幸的是,我不能简单地将所有以下代码放在"回调"函数中,因为外部函数返回依赖于结果.

有没有办法可以处理这个问题,理想情况下无需更改外部函数(myFunction)上的任何内容?

javascript asynchronous async-await ecmascript-6 es6-promise

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

在解决原始承诺之前等待嵌套的 JS 承诺完成

我是 Promises 的新手,我在解决原始承诺之前等待嵌套承诺完成所有执行的概念有点麻烦。

原始代码

function getSomething(text) {
    return new Promise(function (resolve, reject) {
        getElse(text).then(function (items) {
            if (items.length !== 0) {

                /* Stuff here */

                getElseElse(box).then(function (moreItems) {

                    /* Stuff here */

                    return array;
                }.then(function (array) {
                    var promise = new Promise(function (resolve, reject) {
                        /* anotherFunction() is asynchronous */
                        result = anotherFunction(array); <-- Spot 1
                    });
                    promise.then(function () { });
                });

                return resolve(result); <--- Spot 2

            }
            else {
                return resolve(null);
            }
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

更新的代码- 更好,但仍然没有像我想要的那样完全工作。

function …
Run Code Online (Sandbox Code Playgroud)

javascript nested promise

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

A returned Promise with Fetch doesn't respond to .then()

I'm a bit confused here, this part of some async code isn't working. Here's the problem:

export async function active() {
    return new Promise(function(resolve,reject){
        fetch("https://api.spotify.com/v1/me", { //omitted headers to keep it clean
        }).then(response => console.log(response)) <-- This code runs, and will log a response
        .then(data => function(){ <-- but this won't
            console.log("This won't run either")
            if (data.status == 200) {
                console.log(true)
                resolve(data)
            } else {
                console.log(false)
                reject(data)
            }
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

Why isn't the second part running? Sorry, I'm a …

javascript asynchronous

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

Javascript Promise 不进入 then()

我对 JavaScript Promise 有一个问题,其中一个 Promise 没有进入 then()

下面是我试图完成的代码。

背景:我之前没有使用过Promise,但是看过几篇文章。

    function doStart(){        
    var loadedMap = loadBasemap([layer0]);
    loadedMap.then(function (v) {
            view = loadView(MAP_CANVAS_ID, map);
            ...
        });
    ...
}
    
 function loadBasemap(layers) {
    if (LayerSettings && LayerSettings.hasOwnProperty('basemap') && LayerSettings.basemap.hasOwnProperty('baseMapLayers')) {
        new Promise(function () {
            updateToDefaultLayerSetting();
        }).then(function () {
            map = new Map({
                basemap: Basemap.fromJSON(LayerSettings.basemap),
                layers: layers
            });
        });
        return new Promise((resolve, reject) => resolve(map));
    }
    else {...}
}

async function updateToDefaultLayerSetting() {
    console.log("Calling default");
    const result = await actionDefaultBasemap();
    console.log(result);
}

var defaultBasemap;
function …
Run Code Online (Sandbox Code Playgroud)

javascript promise

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