相关疑难解决方法(0)

AngularJS使用UI-Router处理拒绝的响应

我有一个服务,它在Angular中包装我的API调用:

var ConcernService = {

    list: function (items_url) {
        var defer = $q.defer();
        $http({method: 'GET', 
            url: api_url + items_url})
            .success(function (data, status, headers, config) {
                defer.resolve(data, status);
            })
            .error(function (data, status, headers, config) {
                defer.reject(data, status);
            });
        return defer.promise;
    },
Run Code Online (Sandbox Code Playgroud)

然后我的应用程序配置,UI-Router:

    .config(function($stateProvider){

        $stateProvider

        .state('default', {
            url: '/',
            resolve: {
                tasks: function ($stateParams, ConcernService) {
                    return ConcernService.list('tasks/').then(
                        function (tasks)   { return tasks; },
                        function (reason)  { return []; }
                    );
                },
                ...
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

这是最基本的配置,我可以蒙混过关,这基本上只是返回如果一个空的对象403,404 …

promise angularjs angular-ui-router

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

避免延迟反模式

我有一些看起来像这样的代码:

function foo() {

    var deferred;

    deferred = q.defer();

    doSomethingAsync()
        .then(function(result) {
            var resultTransformed = doSomethingSynchronousToTheResult(result);
            deferred.resolve(resultTransformed);
        });

    return deferred.promise;

};
Run Code Online (Sandbox Code Playgroud)

也许:

function foo() {            
    return doSomethingAsync()
        .then(function(result) {
            return doSomethingSynchronousToTheResult(result);
        });       
};
Run Code Online (Sandbox Code Playgroud)

以上是否可以确保转换结果在承诺链中进一步使用?

我怎样才能重构这个以避免延迟的反模式?

javascript promise

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

Angular $ q返回承诺多个$ http调用

我正在进行$ http调用,它遍历多个api中的每一个并返回一个对象中的所有数据.我通常已经准备好在$ http调用时解决.与此类似:

function getAllData(api) {
    return $http({
        method: 'GET',
        url: '/api/' + api
    })
    .then(sendResponseData)
    .catch (sendGetVolunteerError);
}
Run Code Online (Sandbox Code Playgroud)

当前函数我遍历每个api并将api中的每个对象推送到一个数组中,然后将其推送到整个数组中.我有这个功能,返回一个多维数组,需要被展平.

我想在承诺中归还这个,但我要回来了undefined.这是我到目前为止的情况?有没有更好的方法来解决这个问题?

DataService的:

function getSearchData() {
    return {
        loadDataFromUrls: function () {
            var apiList = ["abo", "ser", "vol", "con", "giv", "blo", "par"];
            var deferred = $q.defer();
            var log = [];
            angular.forEach(apiList, function (item, key) {
                var logNew = [];
                $http({
                    method: 'GET',
                    url: '/api/' + item
                }).then(function (response) {
                    angular.forEach(response.data, function (item, key) {
                        this.push(item);
                    }, logNew);
                    return logNew; …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-promise

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

Promises:.done()总是执行,即使.catch()是?

我的承诺问题

我是新手Promises,我一直在阅读Q文档,其中说:

当你到达承诺链的末尾时,你应该返回最后的承诺或结束链.

我已经在我的代码中定义了一个Promise Q.Promise,使用以下console.log命令注销执行跟踪:

function foo(){
   return Q.Promise(function(resolve, reject) {

    doSomething()
    .then(function() {
      console.log('1');
      return doSomething1();
    })
    .then(function() {
      console.log('2');
      return doSomething2();
    })
    .then(function() {
      console.log('3');
      return doSomething3();
    })
    .catch(function(err) {
      console.log('catch!!');
      reject(err);
    })
    .done(function() {
      console.log('done!!');
      resolve();
    });

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

如果每个都doSomethingN()正确执行,一切都按预期工作,我得到预期的跟踪:

1
2
3
done!!
Run Code Online (Sandbox Code Playgroud)

如果任何doSomethingN()失败:

foo()工作正常,因为错误函数回调是每当reject(err)发生时运行的回调:

foo().then(function() { /* */ }, function(err) { /* this runs! */ });

我得到以下跟踪(即doSomething1()失败时):

1 …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise q

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

使用fetch时拒绝承诺

我对如何正确使用fetch感到困惑.即使我收到错误状态,它似乎也解决了.以下代码是否正确(将获取包装在另一个承诺中)?

function a(url, config) {
  if (!config)
    config = {};

  config = Object.assign(config, {
    headers: {
      'content-type': 'application/json;charset=utf-8'
    }
  })
  return new Promise(
    function(resolve, reject) {
      fetch(url, config).then(
        function(res) {
          if (res.status == 200 && res.ok) {
            console.log("Promise resolved")
            resolve(res);
            return;
          }
          console.log("Promise rejected")
          reject(res);
        },
        function(rej) {
          console.log("promise rejected")
          reject(rej);
        }
      )
    }
  )
}

function b() {
  a('/test').then(
    function(res) {
      console.log('success');
      console.log(res)
    },
    function(rej) {
      console.log('Rejected');
      console.log(rej)
    }
  )
}

b();
Run Code Online (Sandbox Code Playgroud)
(以上代码应该通过控制台在chrome中正常运行...只需复制/粘贴)

javascript angularjs ecmascript-6 fetch-api

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

Node.js UnhandledPromiseRejectionWarning即使在捕获之后也是如此

我正在使用Node 7.2.1和新的async/await功能.我也使用像这样的猫鼬本机ES6 Promises -

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
Run Code Online (Sandbox Code Playgroud)

我的代码流是这样的 -

async function getFollowers(){
    try {
        const followers = await User.getFollowersFromMongo(req.params.userId);
        res.send(followers);
    } catch (err) {
        winston.error('Printing Error = ', err);
        res.status(400).send({success: false, error: err});
    }
}

UserSchema.statics.getFollowersFromMongo = async(userId) => {
    try {
        let aggregateQuery = []; //some syntactical error in mongo query to produce exception

        const followers = await User.aggregate(aggregateQuery);
        return followers.map(follower => follower.followerData);
    }
    catch (err) {
        return Promise.reject(err);
    }
};
Run Code Online (Sandbox Code Playgroud)

这段代码非常好用.出现错误时会出现问题.所以我故意修改我的mongoose …

javascript mongoose node.js async-await es6-promise

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

一旦所有嵌套的promises都已解决,就使用Fire Promise.all()

我正在尝试使用他们的Firebase API以递归方式获取Hacker News故事的所有评论.故事有一个kids属性,它是一组代表注释的ID.每个注释都可以有自己的kids属性,指向其子注释,依此类推.我想创建一个整个注释树的数组,看起来像这样:

[{
  'title': 'comment 1', 
  'replies': [{
    'title': 'comment 1.1'
  }, {
    'title': 'comment 1.2'
    'replies': [{
      'title': 'comment 1.2.1'
    }]
  }]
}]
Run Code Online (Sandbox Code Playgroud)

我以为我可以使用以下功能执行此操作:

function getItem(id) {
    return api
        .child(`item/${id}`)
        .once('value')
        .then((snapshot) => {  // this is a Firebase Promise
            let val = snapshot.val()

            if (val.kids) {
                val.replies = val.kids.map((id) => getItem(id))
            }

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

然后在使用以下内容获取整个评论树后收到通知:

getItem(storyId)
    .then(story => {
      // The story and all of its comments should now be loaded …
Run Code Online (Sandbox Code Playgroud)

javascript recursion asynchronous promise

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

承诺类型错误:在非对象上调用函数解析

我对承诺很陌生,认为我可能会混淆从承诺返回并传递给.then.catch的内容。我在下面的注释行上收到 TypeError ,但是当我将其更改为

.then(Promise.resolve)
Run Code Online (Sandbox Code Playgroud)

到 .then((obj) => { Promise.resolve(obj); })

错误消失。这里有什么区别?我是否误解了如何链接承诺?

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.set('debug', true);
var FoodItem = require('../models/FoodItem.js');
var UserFoodItem = require('../models/UserFoodItem.js');
var User = require('../models/User.js');

var StockController = {};
StockController.createUserFoodItem = function(userId, {name, qty}) {
    var userItem = new UserFoodItem({
        user: new mongoose.Types.ObjectId(userId),
        dateAdded: new Date(),
        quantity: qty
    });

    return new Promise((resolve, reject) => {
        FoodItem.findOne({ 'name': name })
            .then((foodItem) => {
                if (foodItem) {
                    userItem.foodItem = foodItem; 
                    userItem.save().then((userFoodItem) …
Run Code Online (Sandbox Code Playgroud)

node.js promise bluebird

6
推荐指数
0
解决办法
6395
查看次数

Promise.all() 不等待异步进程

在 Node.js 中,我尝试循环某些项目,为每个项目完成一个异步过程,然后等待每个项目完成后再开始下一个项目。我一定做错了什么,因为 Promise.all() 没有等待任何异步进程完成!我的代码如下:

getChildLessons() {

 return new Promise((resolve, reject) => {

  Promise.all(

    //nested for loop is needed to get all information in object / arrays
   this.lessons.levels.map((item, i) => {

      item.childlevels.map((childItem, iChild) => {

        return ((i, iChild) => {

          //return async process with Promise.resolve();
          return this.horseman
          .open(childItem.url)
          .html()
          .then((html) => {
            //adding some information to an array
          })
          .then(() => {
              return Promise.resolve();
          }).catch((err) => {
            reject(err);
          });

        })(i, iChild);

      });
  })

  // Promise.all().then()
).then(() => {
  resolve(this.lesson);
}) …
Run Code Online (Sandbox Code Playgroud)

asynchronous node.js promise es6-promise

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

Jest/Typescript 测试 Firebase/Firestore Admin SDK 的最佳实践

我正在编写一个应用程序,其后端编写为节点/express 服务器,通过 firebase 功能上的 Admin SDK 运行 firestore 命令。我想知道测试数据库功能的最佳方法是什么。此类函数的示例如下:

export const deleteDocument = async(id: string): Promise<void> => {
    try {
        await firestore.collection("sampleCollection").doc(id).delete();
    } catch (e) {
        throw new Error(`Could not delete ${id}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想运行一个像这样的单元测试(我知道这里的实际逻辑有点奇怪,但它是即时完成的,并不是问题的重点):

it('should delete a document from the sample collection', async () => {
    //This would already be tested
    const id = await createDocument(...);
    if (id !== undefined) {
      await deleteDocument(id);
      try {
        await getCollective(id);
        expect(true).toBe(false);
      } catch (e) {
        expect(true).toBe(true);
      }
    } else {
      expect(id).toBeDefined();
    } …
Run Code Online (Sandbox Code Playgroud)

firebase typescript jestjs google-cloud-firestore firebase-cli

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