相关疑难解决方法(0)

Javascript可迭代的技术定义是什么?如何测试它?

我一直在实现ES6 Set对象的有用子类.对于我的许多新方法,我想接受一个可以是另一个Set或一个数组的参数,或者我可以迭代的任何东西.我一直在调用我的界面中的"可迭代"并只使用.forEach()它(它适用于Set或Array.示例代码:

// remove items in this set that are in the otherIterable
// returns a count of number of items removed
remove(otherIterable) {
    let cnt = 0;
    otherIterable.forEach(item => {
        if (this.delete(item)) {
            ++cnt;
        }
    });
    return cnt;
}
Run Code Online (Sandbox Code Playgroud)

要么

// add all items from some other iterable to this set
addTo(iterable) {
    iterable.forEach(item => {
        this.add(item);
    });
}
Run Code Online (Sandbox Code Playgroud)

但是,我怀疑我可能并没有像ES6定义的那样支持任何迭代,所以我对Javascript可迭代的真正定义是什么感兴趣,因为ES6规范使用了这个术语?

你如何在ES6 Javascript中测试它?

你应该如何迭代一般的迭代?

我在ES6规范中找到了这样的短语:

如果存在参数iterable,则期望它是一个实现@@ iterator方法的对象,该方法返回一个迭代器对象,该对象生成一个类似于二元素的对象,其第一个元素是一个将用作WeakMap键的值,其第二个元素是与该键关联的值.

但是,这指的@@iterator method是我似乎无法通过该属性名称访问的内容.

javascript iterator iterable ecmascript-6

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

如何在 React 中等待多个异步等待请求

我想在 React 组件中执行以下操作:

const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {

  const result = await someAsyncFunction(item)
  results.push(result)
})
Run Code Online (Sandbox Code Playgroud)

我如何知道所有结果何时返回然后执行某些操作?

如果我在 AngularJS 中使用 $q,我可以这样做

var results = []
someArray.forEach(function(item) {
  var result = someAsyncFunctionThatReturnsAPromise(item);
  results.push(result);
});

$q.all(results).then(function() {
  // do something
});
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous promise reactjs

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

如何在 forEach 循环内等待 Promise

我正在使用一些承诺来获取一些数据,但我在项目中遇到了这个问题。

example1 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo1');
  }, 3000);
});

example2 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo2');
  }, 3000);
});

doStuff = () =>  {
  const listExample = ['a','b','c'];
  let s = "";
  listExample.forEach((item,index) => {
    console.log(item);
    example1().then(() => {
        console.log("First");
        s = item;
    });
    example2().then(() => {
        console.log("Second");
    });
  });
  console.log("The End");
};
Run Code Online (Sandbox Code Playgroud)

如果我在代码中调用 doStuff 函数,结果不正确,我预期的结果如下所示。

RESULT                EXPECTED
a                     a
b                     First
c                     Second
The End               b
First                 First
Second …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous promise es6-promise fetch-api

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

如何修复异步 forEach 推送?

当我调用我自己使用 node.js 开发的 api 时,连接 postgres (Sequelize) 数据库,它返回以下 JSON:

[
  {
    "id": 1,
    "name": "Wallet Name",
    "wallet_type": "MN",
    "icon": "fa fa-bank",
    "color": "#000000",
    "credit_limit": 3000,
    "due_day": 22
  }
]
Run Code Online (Sandbox Code Playgroud)

我只需要,它在每个对象上再返回一行(account_value),该信息位于另一个 javascript 函数中,因此它应该如下所示:

[
  {
    "id": 1,
    "name": "Wallet Name",
    "wallet_type": "MN",
    "icon": "fa fa-bank",
    "color": "#000000",
    "credit_limit": 3000,
    "account_value": 1200.55,
    "due_day": 22
  }
]
Run Code Online (Sandbox Code Playgroud)

我目前的代码是:

[
  {
    "id": 1,
    "name": "Wallet Name",
    "wallet_type": "MN",
    "icon": "fa fa-bank",
    "color": "#000000",
    "credit_limit": 3000,
    "due_day": 22
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,当它返回一个空数组时:

[]
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

我不知道如何修复它(我可以更改我所有的代码)

非常感谢!

javascript foreach asynchronous node.js sequelize.js

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

在 Cypress 循环中,如果条件满足则返回 true,否则迭代结束后返回 false

我需要循环遍历具有相同 CSS 选择器的多个元素,并在 element.text() 与字符串匹配时返回 true。如果没有匹配则最后返回 false。
我尝试了类似下面的方法,但没有成功:

getProfilePresentOrNot(profileName) {
  var flag = 0;
  cy.get('li>div>div>span').each(($el,index,$list) => {
    if ($el.text().includes(profileName)) {
      flag=1;
    }
  });
  return flag;
}
Run Code Online (Sandbox Code Playgroud)

returns 0即使我可以确认 if 块中的条件满足,该函数始终会执行。

javascript automated-tests ui-automation cypress

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

异步/等待在 forEach 中不起作用

尝试使用 async/await 时获取意外令牌 forEach

    export let appState = observable({
        bunny : []
    });

    appState.loadBunny = async function(bugs) {
    bugs.forEach(function(data) {
        let temp = {};
        temp['id'] = data.id;
        temp['site_url'] = data.site_url;
        temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
        temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
        temp['password'] = await decrypt(sessionStorage.getItem('key'), data.password);
        temp['note'] = await decrypt(sessionStorage.getItem('key'), data.note);
        temp['tag'] = await decrypt(sessionStorage.getItem('key'), data.tag);
        temp['created_at'] = data.created_at;
        temp['updated_at'] = data.updated_at;
        runInAction("update state after decrypting data", () => {
            this.bunny.push(temp);
        });

    });
};

    appState.fetch = async function() {
        let xoxo …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous async-await ecmascript-6

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

迭代数组并等待承诺

如何使用 Promise 遍历数据数组并返回数据?我已经看到了一些 promises.push(asyncFunc) 方法,但是我的数组中的一些条目会失败,所以从我收集的信息来看,我不能使用它。

var filesFromDisk = [
    '41679_4_2015-09-06_17-02-12.mp4',
    '41679_4_2015-09-06_17-02-12.smil',
    '41680_4_2015-09-09_10-44-05.mp4'
];

start(filesFromDisk)
    .then((data) => {
        console.log(data); // Want my data here
});
Run Code Online (Sandbox Code Playgroud)

start(dbFiles)从另一个文件开始,这就是为什么我希望在那里返回数据。

function start(dbFiles) {
    var listOfFiles = [],
        promises = [];
    return new Promise((fulfill, reject) => {
        for (var i = 0; i < dbFiles.length; i++) { 
            getMp4(dbFiles[i])
                .then((data) => {
                    listOfFiles = listOfFiles.concat(data);
                    console.log(listOfFiles);
                })
        }
        fulfill(listOfFiles) // Need to happen AFTER for loop has filled listOfFiles
    });
}
Run Code Online (Sandbox Code Playgroud)

因此,对于数组中的每个条目,我想检查具有新扩展名的文件是否存在并读取该文件。如果带扩展名的文件不存在,则执行原始文件。我的Promise.all链正常工作,所有数据都在上面的 for …

javascript node.js promise

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

为什么javascript不等待和forEach并执行下一行

当我在 nodejs 中创建我的 api 并尝试将 mongoose 返回计数推送到新创建的数组时,它不会等待 forEach 并执行 json.res() 并给出空响应。当我使用 setTimeout() 时,它会给出正确的结果。

let newcategories = [];
let service = 0;
const categories = await Category.find({}, '_id name');
categories.forEach(async (category) => {

service = await Service.count({category: category});

newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);

});  /* while executing this forEach it's not wait and execute res.json..*/


console.log('result --- ',result);
console.log('out newcategories is -- ', newcategories);
res.json({status: 200, data: newcategories});
Run Code Online (Sandbox Code Playgroud)

javascript node.js reactjs es6-promise angular

3
推荐指数
2
解决办法
2482
查看次数

确保在另一个之前执行带有异步调用的forEach?

我有一个多forEach循环的函数:

async insertKpbDocument(jsonFile) {
    jsonFile.doc.annotations.forEach((annotation) => {
      annotation.entities.forEach(async (entity) => {
        await this.addVertex(entity);
      });
      annotation.relations.forEach(async (relation) => {
        await this.addRelation(relation);
      });
    });
    return jsonFile;
  }
Run Code Online (Sandbox Code Playgroud)

我需要确保forEach调用该this.addVertex函数的循环中的异步代码在执行下一个函数之前已经完成.

但是当我记录变量时,似乎this.addRelation在第一个循环真正结束之前调用了该函数.

所以我尝试await在每个循环之前添加术语,如下所示:

await jsonFile.doc.annotations.forEach(async (annotation) => {
      await annotation.entities.forEach(async (entity) => {
        await this.addVertex(entity);
      });
      await annotation.relations.forEach(async (relation) => {
        await this.addRelation(relation);
      });
    });
Run Code Online (Sandbox Code Playgroud)

但同样的行为.

也许是日志函数有延迟?有任何想法吗?

javascript promise typescript

3
推荐指数
2
解决办法
321
查看次数

如何使用批处理在Firestore中更新500多个文档?

我正在尝试使用包含500多个文档的集合中timestampFirestoreadmin时间戳更新字段。

const batch = db.batch();
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp();

db
  .collection('My Collection')
  .get()
  .then((docs) => {
    serverTimestamp,
  }, {
    merge: true,
  })
  .then(() => res.send('All docs updated'))
  .catch(console.error);
Run Code Online (Sandbox Code Playgroud)

这引发一个错误

{ Error: 3 INVALID_ARGUMENT: cannot write more than 500 entities in a single call
    at Object.exports.createStatusError (C:\Users\Growthfile\Desktop\cf-test\functions\node_modules\grpc\src\common.js:87:15)
    at Object.onReceiveStatus (C:\Users\Growthfile\Desktop\cf-test\functions\node_modules\grpc\src\client_interceptors.js:1188:28)
    at InterceptingListener._callNext (C:\Users\Growthfile\Desktop\cf-test\functions\node_modules\grpc\src\client_interceptors.js:564:42)
    at InterceptingListener.onReceiveStatus (C:\Users\Growthfile\Desktop\cf-test\functions\node_modules\grpc\src\client_interceptors.js:614:8)
    at callback (C:\Users\Growthfile\Desktop\cf-test\functions\node_modules\grpc\src\client_interceptors.js:841:24)
  code: 3,
  metadata: Metadata { _internal_repr: {} },
  details: 'cannot write more than 500 entities in a single …
Run Code Online (Sandbox Code Playgroud)

firebase firebase-admin google-cloud-firestore

3
推荐指数
4
解决办法
1543
查看次数