Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 试图在数组函数上使用async/await_Arrays_Node.js_Async Await - Fatal编程技术网

Arrays 试图在数组函数上使用async/await

Arrays 试图在数组函数上使用async/await,arrays,node.js,async-await,Arrays,Node.js,Async Await,我正试图简化我的测试脚手架的快速后端。我希望使用数组一个接一个地执行db插入,而不是多次调用单个记录插入例程(在检查结果时似乎存在同步问题) 这是我到目前为止所拥有的。。。但我似乎在搞异步等待。测试失败了,因为我得到了0个体长,可能还有一个插入。知道我哪里出错了吗 async function asyncForEach (array, callback) { for (let index = 0; index < array.length; index++) { await

我正试图简化我的测试脚手架的快速后端。我希望使用数组一个接一个地执行db插入,而不是多次调用单个记录插入例程(在检查结果时似乎存在同步问题)

这是我到目前为止所拥有的。。。但我似乎在搞异步等待。测试失败了,因为我得到了0个体长,可能还有一个插入。知道我哪里出错了吗


async function asyncForEach (array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  };
}

async function insertTemplates(myTemplatesArray) {
  const client = new Client(dbConfig);
  client.connect();
  await asyncForEach(
    myTemplatesArray,
    async (myTemplate) => {
      let { name, status, version } = myTemplate;
      await client.query(
        SQL`INSERT INTO templates (name, status, version )
        VALUES (${name}, ${status}, ${version})`)
        .catch( err => console.error(err) );
    });
  client.end();
}

function randomTemplate() {
  const template = {
    name: faker.internet.userName(),
    status: faker.hacker.phrase(),
    version: String(faker.random.number())
  };
  return template;
}

function clean_db(){
  const client = new Client(dbConfig);
  client.connect();
  client.query(
    `TRUNCATE TABLE "templates";
    ALTER SEQUENCE "templates_id_seq" RESTART WITH 1;`)
    .catch( err => { console.error(err); } )
    .then( () => client.end() );
}

describe('When there are 1 or more records in the table', () => {

    const templ1 = randomTemplate();
    const templ2 = randomTemplate();
    const templ3 = randomTemplate();

    beforeEach(async () => {
      await clean_db();
      await insertTemplates([templ1,templ2,templ3]);
    });

    afterEach(async () => {
      await clean_db();
    });

    test('It should respond with a 200 status', async done => {
      const response = await template(app).get('/templates');
      expect(response.status).toBe(200);
      done();
    });

    test('It should respond with an JSON array of records', async done => {
      const response = await template(app).get('/templates');
      expect(response.body.length).toBe(3);
      done();
    });

    test('It should respond with the correct records', async done => {
      templ1.id = 1;
      templ2.id = 2;
      templ3.id = 3;

      const response = await template(app).get('/templates');
      expect(response.body).toStrictEqual([templ1,templ2,templ3]);
      done();
    });
  });
});


异步函数asyncForEach(数组、回调){
for(让index=0;index{
让{name,status,version}=myTemplate;
等待client.query(
SQL`插入模板(名称、状态、版本)
值(${name}、${status}、${version})`)
.catch(err=>console.error(err));
});
client.end();
}
函数模板(){
常量模板={
名称:faker.internet.userName(),
状态:faker.hacker.phrase(),
版本:字符串(faker.random.number())
};
返回模板;
}
函数clean_db(){
const client=新客户端(dbConfig);
client.connect();
client.query(
`截断表“模板”;
更改顺序“templates\u id\u seq”用1;`)重新启动
.catch(err=>{console.error(err);})
。然后(()=>client.end());
}
description('当表中有1条或多条记录时',()=>{
const templat1=randomTemplate();
常量模板2=随机模板();
常量模板3=随机模板();
beforeach(异步()=>{
等待清洁_db();
等待insertTemplates([templ1,templ2,templ3]);
});
每次之后(异步()=>{
等待清洁_db();
});
测试('它应该以200状态响应',异步完成=>{
const response=wait-template(app.get('/templates');
expect(response.status),toBe(200);
完成();
});
test('它应该用记录的JSON数组响应',async done=>{
const response=wait-template(app.get('/templates');
期望值(反应、体长)、toBe(3);
完成();
});
test('它应该用正确的记录响应',async done=>{
temp1.id=1;
temp2.id=2;
temp3.id=3;
const response=wait-template(app.get('/templates');
expect(response.body).toStrictEqual([temp1,temp2,temp3]);
完成();
});
});
});

我认为您的测试没有按预期工作的原因是您正在打破clean_db()中的承诺链。。也许还有其他一些功能。这是非常容易做到这一点时,与承诺的工作

我建议确保clean_db返回承诺,例如:

function clean_db(){
    const client = new Client(dbConfig);
    client.connect();
    // return promise to keep chain intact.
    return client.query(
        `TRUNCATE TABLE "templates";
        ALTER SEQUENCE "templates_id_seq" RESTART WITH 1;`)
        .catch( err => { console.error(err); } )
        .then( () => client.end() );
}
我想client.end()会返回一些东西。。这将导致clean_db()返回一个承诺,以便wait调用将实际等待

对于insertTemplates,我也会这样做,例如返回client.end()的结果


另外,请确保传递给asyncForEach的回调返回承诺。。我不确定它是否能工作。

值(${name},${status},${version})
似乎没有被转义,我无法想象插入是否能工作。侧节点:您可以去掉
异步完成=>{
完成();
并将其替换为:
异步()=>{/code>值(${name},${status},${version})
在后面的刻度中,我使用的是“sql模板字符串”包,因此
sql
前缀/调用,我不得不说这是一个相当不错的包。谢谢,下次必须注意后面刻度前面的东西。Terry,先生,您是一位绅士和学者。CleanDB()不兑现承诺显然就是承诺——只是改变了,而且考试第一次通过了。非常感谢!很高兴听到这个消息,我自己也被抓过好几次:-)。。。
async function insertTemplates(myTemplatesArray) {
  const client = new Client(dbConfig);
  client.connect();
  await asyncForEach(
    myTemplatesArray,
    async (myTemplate) => {
      let { name, status, version } = myTemplate;
      // Return promise to calling proc.
      return client.query(
        SQL`INSERT INTO templates (name, status, version )
        VALUES (${name}, ${status}, ${version})`)
        .catch( err => console.error(err) );
    });
    return client.end();
}